import React, { Component, createRef } from 'react'
import { Popconfirm } from 'antd'
import { connect } from 'react-redux'

// import { canvas } from '../component/Canvas'

import { toggleDrag, toggleScale, toggleFreeDraw, toggleErase } from '../redux/action/canvasActions'
import {
	undoFreeDrawing,
	redoFreeDrawing,
	clearPainting,
	clearHistory,
} from '../redux/action/freeDrawingActions'

class ToolBar extends Component {
	constructor(props) {
		super(props)
		this.toolbar = createRef()
		this.funcArr = [
			state => this.props.toggleDrag(state),
			state => this.props.toggleScale(state),
			state => this.props.toggleFreeDraw(state),
			state => this.props.toggleErase(state),
			// state => canvas.setState({ useFill: state }),
		]
		this.state = {
			lastSelectedIdx: -1,
			selectedIdx: 0,
		}
	}
	handleClick = e => {
		const selectedIdx = this.children.findIndex(ele => ele === e.target)
		if (selectedIdx === -1 || selectedIdx > this.funcArr.length - 1) return
		const lastSelectedIdx =
			selectedIdx !== this.state.selectedIdx
				? this.state.selectedIdx
				: this.state.lastSelectedIdx
		this.funcArr[selectedIdx](true)
		lastSelectedIdx !== -1 && this.children[lastSelectedIdx].classList.remove('selected')
		this.children[selectedIdx].classList.add('selected')
		lastSelectedIdx !== -1 && this.funcArr[lastSelectedIdx](false)
		this.setState({ lastSelectedIdx, selectedIdx })
	}
	undoFreeDrawing = () => {
		this.props.undoFreeDrawing()
	}
	redoFreeDrawing = () => {
		this.props.redoFreeDrawing()
	}
	render() {
		return (
			<aside className='left-side-tool' onClick={this.handleClick} ref={this.toolbar}>
				<div className='iconfont icon-guangbiao'></div>
				<div className='iconfont icon-fangda-'></div>
				<div className='iconfont icon-pan_icon-copy'></div>
				<div className='iconfont icon-xiangpi'></div>
				{/* <div className='iconfont icon-tianchong'></div> */}
				<Popconfirm
					placement='rightTop'
					title='你确定要清空屏幕内的自由绘画吗？'
					onConfirm={this.props.clearPainting}
					okText='是'
					cancelText='否'
				>
					<div className='iconfont icon-qingkong'></div>
				</Popconfirm>
				<div className='iconfont icon-chexiao' onClick={this.undoFreeDrawing}></div>
				<div
					className='iconfont icon-chexiao'
					onClick={this.redoFreeDrawing}
					style={{ transform: 'scaleX(-1)' }}
				></div>
				<Popconfirm
					placement='rightTop'
					title='你确定要清空自由绘画的所有历史吗？'
					onConfirm={this.props.clearHistory}
					okText='是'
					cancelText='否'
				>
					<div className='iconfont icon-delete' ref={this.clearHistory}></div>
				</Popconfirm>
			</aside>
		)
	}
	componentDidMount() {
		this.children = Array.from(this.toolbar.current.children)
	}
}

const mapState = state => {
	return state.canvasReducer
}

export default connect(mapState, {
	toggleDrag,
	toggleScale,
	toggleFreeDraw,
	toggleErase,
	undoFreeDrawing,
	redoFreeDrawing,
	clearPainting,
	clearHistory,
})(ToolBar)
